package com.lcc.dingtalk.robot.base.aspect;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.lcc.dingtalk.robot.base.enums.ENMsgCode;
import com.lcc.dingtalk.robot.pojo.message.resp.DingTalkBaseResp;
import com.lcc.dingtalk.robot.pojo.message.resp.DingTalkTextResp;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author lincc
 * @version 1.0  2018/11/27
 */
@Aspect
@Component
public class SystemAspect {

    @Around("execution(* com.lcc.dingtalk.robot.controller..*.*(..))")
    public Object exceptionHandle(ProceedingJoinPoint pjp) {
        DingTalkBaseResp resp = new DingTalkBaseResp();
        Logger logger = LoggerFactory.getLogger(pjp.getTarget().getClass());
        String signatureName = pjp.getSignature().getName();
        String entryParameter = "方法" + signatureName +
                "请求参数：" +
                JSONUtil.toJsonStr(pjp.getArgs());
        logger.info(entryParameter);
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        String resultType = methodSignature.getMethod().getReturnType().getSimpleName();
        try {
            //目前切面只处理DingTalkBaseResp
            if (!"DingTalkBaseResp".equals(resultType)) {
                return pjp.proceed();
            }
            resp = (DingTalkBaseResp) pjp.proceed();
            //下载文件等不需要返回值的特殊处理
            if (ObjectUtil.isNull(resp)) {
                return DingTalkTextResp.context("返回信息为空");
            }
            if (resp.getMsgtype() == null) {
                return DingTalkTextResp.context("返回格式有误");
            }
            return resp;
        } catch (Throwable throwable) {
            logger.error("执行发生异常",throwable);
            return DingTalkTextResp.context(ENMsgCode.SYSTEM_EXCEPTION.getLabel());
        } finally {
            String logStr;
            if (!"DingTalkBaseResp".contains(resultType) || ObjectUtil.isNull(resp)) {
                logStr = "不打印";
            }else{
                logStr = JSONUtil.toJsonStr(resp);
            }
            logger.info("方法{}返回结果：{}", pjp.getSignature().getName(), logStr);

        }
    }

}
